package com.axinfu.util.enhance;

import com.alibaba.fastjson.JSONObject;
import com.axinfu.util.EmptyUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 快速构建Json对象
 * ps:取名为JsonQ的意义在于，Q位于键盘左上角
 * ，由左手小指负责，小指平时使用较少
 * ，这样可以多锻炼，利于开发右脑
 *
 * @author zjn
 * @since 2022/3/23
 */
public class JsonQ extends JSONObject {

    public JsonQ() {
        super();
    }

    public JsonQ(Map<String, Object> map) {
        super(map);
    }

    public JsonQ(boolean ordered) {
        super(ordered);
    }

    public JsonQ(int initialCapacity) {
        super(initialCapacity);
    }

    public JsonQ(int initialCapacity, boolean ordered) {
        super(initialCapacity, ordered);
    }

    public static JsonQ create() {
        return new JsonQ();
    }

    public static JsonQ create(Map<String, Object> map) {
        return new JsonQ(map);
    }

    public static JsonQ create(String json) {
        return create().set(json);
    }

    public static JsonQ create(boolean ordered) {
        return new JsonQ(ordered);
    }

    public static JsonQ create(int initialCapacity) {
        return new JsonQ(initialCapacity);
    }

    public static JsonQ create(int initialCapacity, boolean ordered) {
        return new JsonQ(initialCapacity, ordered);
    }

    public static JsonQ by(String key, Object value) {
        return new JsonQ().set(key, value);
    }

    public static JsonQ by(Map<String, Object> map) {
        return new JsonQ().set(map);
    }

    public JsonQ set(String key, Object value) {
        if (EmptyUtil.isNotEmpty(key)) {
            super.put(key, value);
        }
        return this;
    }

    public JsonQ set(Map<String, Object> map) {
        if (EmptyUtil.isNotEmpty(map)) {
            super.putAll(map);
        }
        return this;
    }

    public JsonQ set(String json) {
        set(parseObject(json));
        return this;
    }

    public JsonQ delete(String key) {
        super.remove(key);
        return this;
    }

    @SuppressWarnings("unchecked")
    public <T> T getAs(String key) {
        return (T) get(key);
    }

    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>(1);
        map.putAll(this);
        return map;
    }

    public Map<String, String> toMapString() {
        Map<String, String> map = new HashMap<>(1);
        for (Entry<String, Object> entry : this.entrySet()) {
            map.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return map;
    }
}
